<?php
/**
 * releases actions.
 *
 * @package    IPLIFE
 * @subpackage releases
 * @author     alexey.shapran@gmail.com
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class releasesActions extends sfActions
{
	public function executeIndex(sfWebRequest $request)
	{
		//		$this->relizes = Reliz::getLastRelizes(sfConfig::get('app_max_per_page',10));
		$this->pager = new sfDoctrinePager('Reliz', sfConfig::get('app_max_per_page'));

		$q = Doctrine_Query::create()
		->from('reliz r')
		->leftJoin('r.RelizCategory category')
		->where('is_published = 1')
		->orderBy('r.updated_at DESC');

		$this->pager->setQuery($q);
		$this->pager->setPage($request->getParameter('page', 1));
		$this->pager->init();				
		
		$response = $this->getResponse();		
		$response->addMeta('keywords', SettingsData::Get_it(SettingsData::REL_KEY));
		$response->addMeta('description', SettingsData::Get_it(SettingsData::REL_DESC));
		$response->setTitle(sfConfig::get('app_title')." | ".SettingsData::Get_it(SettingsData::REL_TITLE)  );
		
		//$this->setTemplate('category');
	}

	/**
	 * Get View of selected article's category
	 *
	 * @author	Alexey Shapran <alexey.shapran@gmail.com>
	 * @param sfRequest $request A request object [category_alias]
	 */
	public function executeCategory(sfWebRequest $request)
	{
		$this->Category = $this->getRoute()->getObject();
		$this->forward404Unless($this->Category);

		$query = Doctrine_Query::create()
		->from('reliz r')
		->leftJoin('r.RelizCategory category')
		->orderBy('r.updated_at DESC')
		->limit(sfConfig::get('app_max_per_page',10))
		->where("category_id = ?", array($this->Category->id))
		->andWhere("is_published = 1");

		$this->relizes = $query->execute();
	}

	/**
	 * Get View of selected reliz
	 *
	 * @author	Alexey Shapran <alexey.shapran@gmail.com>
	 * @param sfRequest $request A request object
	 */
	public function executeView(sfWebRequest $request)
	{
		$this->reliz = $this->getRoute()->getObject();
		$this->forward404Unless($this->reliz);

		$response = $this->getResponse();
		$response->addMeta('keywords', $this->reliz['keywords']);
		$response->addMeta('description', $this->reliz['description']);
		$response->setTitle(sfConfig::get('app_title')." | ".$this->reliz['title']);
	}

	/**
	 * Get list of relizes by Tagname
	 *
	 * @author	Alexey Shapran <alexey.shapran@gmail.com>
	 * @param sfRequest $request A request object
	 */
	public function executeTags(sfWebRequest $request)
	{
		$this->tag = rtrim(ltrim($request->getParameter('tag')));
		$this->forward404Unless($this->tag);
		
		$this->relizes = Reliz::getByTag($this->tag);

	}

	// uploads images

	public function executeUpload(sfWebRequest $request)
	{
		$allowed_types = array('image/jpeg','image/gif','image/png');
		if( $file = $request->getFiles('userfile') ){
				
			if ( in_array($file['type'],$allowed_types) && is_file($file['tmp_name']) ) {
				$fileName = sha1(time()).'.'.$this->__getExtension($file['type']);
				$dest = sfConfig::get('sf_upload_dir') . DIRECTORY_SEPARATOR . $request->getParameter('object_enity') . DIRECTORY_SEPARATOR . $fileName;
				move_uploaded_file($file['tmp_name'],$dest);

				$AdditionalImage = new AdditionalImage();
				$AdditionalImage->entity_type = $request->getParameter('object_enity');
				$AdditionalImage->entity_id = $request->getParameter('object_id');
				$AdditionalImage->image = $fileName;
				$AdditionalImage->save();

				$json_response = array('imageid'=>$AdditionalImage->id,'filename'=>$fileName);
				return $this->renderText(json_encode($json_response));
			} else {
				$err = array("error"=>"Некорректный формат. Только jpg,gif,png");
				return $this->renderText(json_encode($err));
			}
		}
		$err = array("error"=>"Ошибка загрузки файла");
		return $this->renderText(json_encode($err));
	}

	public function executeRemove_image(sfWebRequest $request)
	{
		if( !$request->isXmlHttpRequest() )
		$this->redirect('@homepage');

		if( !$request->getParameter('image_id'))
		return $this->renderText('Не указан идентификатор картинки');

		$additional_image = Doctrine::getTable('AdditionalImage')->find($request->getParameter('image_id'));
		if( $additional_image ) {
			unlink(sfConfig::get('sf_upload_dir') . DIRECTORY_SEPARATOR . 'relizes' . DIRECTORY_SEPARATOR . $additional_image->image );
			//TODO: add method for deleting by hash
			$additional_image->delete();
			return $this->renderText('success');
		}
		return $this->renderText('Ошибка удаления');
	}

	private function __getExtension($mime_type)
	{
		switch($mime_type) {
			case "image/jpeg": return 'jpg';
			break;
			case "image/gif": return 'gif';
			break;
			case "image/png": return 'png';
			break;
		}
	}
}